<?php
class ome_order_fail{

    private $_obj_alias = array(
        'goods'       => '商品',
        'pkg'         => '促销类',
        'gift'        => '赠品',
        'giftpackage' => '礼包',
    );

    public function batchModifyOrder(&$cursor_id,$params){
        //danny_freeze_stock_log
        define('FRST_TRIGGER_OBJECT_TYPE','订单：失败订单恢复批量修改');
        define('FRST_TRIGGER_ACTION_TYPE','ome_order_fail：batchModifyOrder');
        $oldPbn = $params['sdfdata']['oldPbn'];
        $pbn = $params['sdfdata']['pbn'];
        $opinfo = $params['opinfo'];
        foreach($params['sdfdata']['orderId'] as $val){
            $this->addFailOrderLog($val,$opinfo);//失败订单操作日志记录添加
            $this->modifyOrderItemsByBn($val,$oldPbn,$pbn);
        }
        return false;
    }

    public function modifyOrder($order_id){
        $orderObj = app::get('ome')->model('orders');
        $order = $orderObj->dump($order_id,'*',array('order_objects'=>array('*',array('order_items'=>array('*')))));
        $is_delete = false;

        if ($order['is_fail'] == 'true'){
            foreach($order['order_objects'] as $obj=>$items){
                if($items['goods_id'] <= 0 || empty($items['bn'])){
                    $is_delete = true;
                    break;
                }
                
                //不存在order_items 保持订单为失败订单
                if(!isset($items['order_items'])){
                    $is_delete = true;
                    break;
                }

                foreach($items['order_items'] as $key=>$item){
                    if($item['product_id']<=0 || !isset($item['product_id'])){
                        $is_delete = true;
                        break;
                    }
                }
            }

            //只要有个内容失败，这个订单还是失败订单，不变
            if($is_delete){
                $data = array('edit_status'=>'true');
                $orderObj->update($data,array('order_id' =>$order_id));
                return false;
            }

            //修正订单
            $orderData['is_fail'] = 'false';
            $orderData['archive'] = 0;
            $orderObj->update($orderData,array('order_id' =>$order_id));
        }
        return true;
    }

    public function modifyOrderItems($order_id,$oldPbn,$pbn){

        $this->addFailOrderLog($order_id);//失败订单操作日志记录添加

        $orderObj = app::get('ome')->model('orders');
        $itemObj = app::get('ome')->model('order_items');
        $Oorder_objects = app::get('ome')->model('order_objects');

        #[拆单]修复_淘宝平台_订单进入ERP的原始数据 ExBOY
        $modify_order_oid    = array();
        
        //先更新订单为不可编辑
        $data = array('edit_status'=>'false');
        $orderObj->update($data,array('order_id' =>$order_id));

        $orderInfo = $orderObj->getList('shop_id,ship_status, shop_type, order_bn',array('order_id'=>$order_id));

        if($pbn){
            $salesMLib = kernel::single('material_sales_material');
            
            foreach($pbn as $obj_id=>$bn){
                //获取对应的obj层数据
                $objInfo = $Oorder_objects->getList('*',array('obj_id'=>$obj_id), 0 , 1);

                //销售物料没对上，进行修复
                $salesMInfo = $salesMLib->getSalesMByBn($orderInfo[0]['shop_id'],$bn);
                if($salesMInfo){
                    $basicMInfos = $salesMLib->getBasicMBySalesMId($salesMInfo['sm_id']);
                    if($basicMInfos){
                        //如果是促销类销售物料
                        if($salesMInfo['sales_material_type'] == 2){
                            $obj_type = 'pkg';

                            //item层关联基础物料平摊销售价
                            $salesMLib->calProSaleMPriceByRate($objInfo[0]['sale_price'], $basicMInfos);
                            $quantity = $objInfo[0]['quantity'] ? $objInfo[0]['quantity'] : 1;
                            //组织item数据
                            foreach($basicMInfos as $k => $basicMInfo){
                                //$basicMInfo['retail_price'] ? $basicMInfo['retail_price'] : 0.00
                                $sendnum = $orderInfo[0]['ship_status'] == '0' ? 0 : $basicMInfo['number']*$quantity;

                                $order_items[] = array(
                                    'shop_goods_id'   => $objInfo[0]['shop_goods_id'] ? $objInfo[0]['shop_goods_id'] : 0,
                                    'product_id'      => $basicMInfo['bm_id'] ? $basicMInfo['bm_id'] : 0,
                                    'shop_product_id' => 0,
                                    'bn'              => $basicMInfo['material_bn'],
                                    'name'            => $basicMInfo['material_name'],
                                    'cost'            => $basicMInfo['cost'] ? $basicMInfo['cost'] : 0.00,
                                    'price'           => $basicMInfo['rate_price'] ? bcdiv($basicMInfo['rate_price'], $basicMInfo['number']*$quantity, 2) : 0.00,
                                    'pmt_price'       => 0.00,
                                    'sale_price'      => $basicMInfo['rate_price'] ? $basicMInfo['rate_price'] : 0.00,
                                    'amount'          => $basicMInfo['rate_price'] ? $basicMInfo['rate_price'] : 0.00,
                                    'weight'          => $basicMInfo['weight'] ? $basicMInfo['weight'] : 0.00,
                                    'quantity'        => $basicMInfo['number']*$quantity,
                                    'addon'           => '',
                                    'item_type'       => 'pkg',
                                    'delete'          => ($objInfo[0]['delete'] == 'true') ? 'true' : 'false',
                                    'sendnum'         => $sendnum,
                                );
                            }
                        }else{
                            $obj_type = ($salesMInfo['sales_material_type'] == 1) ? 'goods' : 'gift';
                            $item_type = ($obj_type == 'goods') ? 'product' : 'gift';

                            if($obj_type == 'gift'){
                                //直接取object层的,不用做处理
                            }

                            //普通销售物料
                            foreach($basicMInfos as $k => $basicMInfo){
                                
                                $addon = '';
                                if ($objInfo[0]['product_attr']) {
                                    $addon = serialize(array('product_attr'=>$objInfo[0]['product_attr']));
                                }
                                $quantity = $objInfo[0]['quantity'] ? $objInfo[0]['quantity'] : 1;
                                $subtotal = $objInfo[0]['amount'] ? (float)$objInfo[0]['amount'] : bcmul((float)$objInfo[0]['price'], $quantity,3);
                                $sendnum = $orderInfo[0]['ship_status'] == '0' ? 0 : $objInfo[0]['sendnum']*$basicMInfo['number'];

                                //普通销售物料item层数据以object为主,原本就是1:1的两层结构,item合并object,item层数据真实
                                $order_items[] = array(
                                    'shop_goods_id'   => $objInfo[0]['shop_goods_id'] ? $objInfo[0]['shop_goods_id'] : 0,
                                    'product_id'      => $basicMInfo['bm_id'] ? $basicMInfo['bm_id'] : 0,
                                    'shop_product_id' => $objInfo[0]['shop_product_id'] ? $objInfo[0]['shop_product_id'] : 0,
                                    'bn'              => $basicMInfo['material_bn'],
                                    'name'            => $basicMInfo['material_name'],
                                    'cost'            => (float)$objInfo[0]['cost'] ? $objInfo[0]['cost'] : $basicMInfo['cost'],
                                    'price'           => (float)$objInfo[0]['price'],
                                    'pmt_price'       => (float)$objInfo[0]['pmt_price'],
                                    'sale_price'      => (isset($objInfo[0]['sale_price']) && is_numeric($objInfo[0]['sale_price']) && -1 != bccomp($objInfo[0]['sale_price'], 0, 3) ) ? $objInfo[0]['sale_price'] : bcsub($subtotal, (float)$item['pmt_price'],3),
                                    'amount'          => $subtotal,
                                    'weight'          => (float)$objInfo[0]['weight'] ? $objInfo[0]['weight'] : ($basicMInfo['weight'] ? $basicMInfo['weight'] : 0.00),
                                    'quantity'        => $basicMInfo['number']*$quantity,
                                    'addon'           => $addon,
                                    'item_type'       => $item_type,
                                    'delete'          => ($objInfo[0]['delete'] == 'true') ? 'true' : 'false',
                                    'sendnum'         => $sendnum,
                                );
                            }
                        }
                    }else{
                        //找不到对应的基础物料
                        continue;
                    }
                    
                    #修复_淘宝平台_原始属性值 ExBOY
                    if($orderInfo[0]['shop_type'] == 'taobao')
                    {
                        $modify_order_oid[]    = array(
                                                            'order_id'=>$order_id,
                                                            'order_bn'=>$orderInfo[0]['order_bn'],
                                                            'obj_id'=>$objInfo[0]['obj_id'],
                                                            'old_bn'=>$oldPbn[$obj_id],
                                                            'new_bn'=>$salesMInfo['sales_material_bn'],
                                                        );
                    }
                    
                }else{
                    //找不到对应的销售物料
                    continue;
                }

                //原来两层结构都有问题失败的
                if($objInfo[0]['goods_id'] <= 0 || empty($objInfo[0]['bn'])){
                    $newOrder['order_objects'][] = array(
                        'obj_id' => $objInfo[0]['obj_id'],
                        'goods_id'      => $salesMInfo['sm_id'] ? $salesMInfo['sm_id'] : 0,
                        'bn'            => $bn ? $bn : null,
                        'obj_type'      => $obj_type,
                        'obj_alias'     => $this->_obj_alias[$obj_type] ? $this->_obj_alias[$obj_type] : '',
                        'order_items'   => $order_items,
                    );

                    $obj_shop_freeze[$objInfo[0]['obj_id']] = $objInfo[0]['quantity'];
                    $obj_status[$objInfo[0]['obj_id']] = $objInfo[0]['delete'];
                }else{
                    //原来绑定基础物料item有问题失败的
                    $newOrder['order_objects'][] = array(
                        'obj_id' => $objInfo[0]['obj_id'],
                        'order_items'   => $order_items,
                    );
                }

                //注销上一轮的order_items
                unset($order_items);
            }
        }

        if($newOrder){
            $basicMStockLib = kernel::single('material_basic_material_stock');
            $salesMShopFreezeLib = kernel::single('material_sales_material_shop_freeze');

            $newOrder['order_id'] = $order_id;
            $res = $orderObj->save($newOrder);
            if($res){
                foreach($newOrder['order_objects'] as $ok => $obj){
                    if($obj['goods_id'] > 0 && $obj_status[$obj['obj_id']] == 'false'){
                        //obj层 销售物料，店铺货品冻结
                        $salesMShopFreezeLib->freeze($orderInfo[0]['shop_id'], $obj['goods_id'], $obj_shop_freeze[$obj['obj_id']]);
                    }

                    foreach($obj['order_items'] as $ik =>$item){
                        if($item['product_id'] > 0 && $item['delete'] == 'false'){
                            //item层基础物料冻结
                            $basicMStockLib->freeze($item['product_id'],(intval($item['quantity'])-intval($item['sendnum'])));
                        }
                    }
                }
            }
        }
        
        #修复_淘宝平台_原始属性值 ExBOY
        if($modify_order_oid)
        {
            $this->modifyOrderOid($modify_order_oid);
        }

        //修正为正常订单
        if($this->modifyOrder($order_id)){
            return true;
        }else{
            return false;
        }
    }

    public function modifyOrderItemsByBn($order_id,$oldPbn,$pbn){
        $orderObj = app::get('ome')->model('orders');
        $itemObj = app::get('ome')->model('order_items');
        $Oorder_objects = app::get('ome')->model('order_objects');

        #[拆单]修复_淘宝平台_订单进入ERP的原始数据 ExBOY
        $modify_order_oid    = array();
        
        $data = array('edit_status'=>'false');
        $orderObj->update($data,array('order_id' =>$order_id));

        $orderInfo = $orderObj->getList('shop_id,ship_status, shop_type, order_bn',array('order_id'=>$order_id));

        if($oldPbn && $pbn){
            $salesMLib = kernel::single('material_sales_material');
            
            foreach($pbn as $key=>$bn){
                //获取对应的obj层数据
                $objInfo = $Oorder_objects->getList('*',array('bn'=>$oldPbn[$key], 'order_id'=>$order_id), 0 , 1);

                //销售物料没对上，进行修复
                $salesMInfo = $salesMLib->getSalesMByBn($orderInfo[0]['shop_id'],$bn);
                if($salesMInfo){
                    $basicMInfos = $salesMLib->getBasicMBySalesMId($salesMInfo['sm_id']);
                    if($basicMInfos){
                        //如果是促销类销售物料
                        if($salesMInfo['sales_material_type'] == 2){
                            $obj_type = 'pkg';

                            //item层关联基础物料平摊销售价
                            $salesMLib->calProSaleMPriceByRate($objInfo[0]['sale_price'], $basicMInfos);
                            $quantity = $objInfo[0]['quantity'] ? $objInfo[0]['quantity'] : 1;
                            //组织item数据
                            foreach($basicMInfos as $k => $basicMInfo){
                                //$basicMInfo['retail_price'] ? $basicMInfo['retail_price'] : 0.00
                                $sendnum = $orderInfo[0]['ship_status'] == '0' ? 0 : $basicMInfo['number']*$quantity;

                                $order_items[] = array(
                                    'shop_goods_id'   => $objInfo[0]['shop_goods_id'] ? $objInfo[0]['shop_goods_id'] : 0,
                                    'product_id'      => $basicMInfo['bm_id'] ? $basicMInfo['bm_id'] : 0,
                                    'shop_product_id' => 0,
                                    'bn'              => $basicMInfo['material_bn'],
                                    'name'            => $basicMInfo['material_name'],
                                    'cost'            => $basicMInfo['cost'] ? $basicMInfo['cost'] : 0.00,
                                    'price'           => $basicMInfo['rate_price'] ? bcdiv($basicMInfo['rate_price'], $basicMInfo['number']*$quantity, 2) : 0.00,
                                    'pmt_price'       => 0.00,
                                    'sale_price'      => $basicMInfo['rate_price'] ? $basicMInfo['rate_price'] : 0.00,
                                    'amount'          => $basicMInfo['rate_price'] ? $basicMInfo['rate_price'] : 0.00,
                                    'weight'          => $basicMInfo['weight'] ? $basicMInfo['weight'] : 0.00,
                                    'quantity'        => $basicMInfo['number']*$quantity,
                                    'addon'           => '',
                                    'item_type'       => 'pkg',
                                    'delete'          => ($objInfo[0]['delete'] == 'true') ? 'true' : 'false',
                                    'sendnum'         => $sendnum,
                                );
                            }
                        }else{
                            $obj_type = ($salesMInfo['sales_material_type'] == 1) ? 'goods' : 'gift';
                            $item_type = ($obj_type == 'goods') ? 'product' : 'gift';

                            if($obj_type == 'gift'){
                                //直接取object层的,不用做处理
                            }
                            //普通销售物料
                            foreach($basicMInfos as $k => $basicMInfo){
                                
                                $addon = '';
                                if ($objInfo[0]['product_attr']) {
                                    $addon = serialize(array('product_attr'=>$objInfo[0]['product_attr']));
                                }
                                $quantity = $objInfo[0]['quantity'] ? $objInfo[0]['quantity'] : 1;
                                $subtotal = $objInfo[0]['amount'] ? (float)$objInfo[0]['amount'] : bcmul((float)$objInfo[0]['price'], $quantity,3);
                                $sendnum = $orderInfo[0]['ship_status'] == '0' ? 0 : $objInfo[0]['sendnum']*$basicMInfo['number'];

                                //普通销售物料item层数据以object为主,原本就是1:1的两层结构,item合并object,item层数据真实
                                $order_items[] = array(
                                    'shop_goods_id'   => $objInfo[0]['shop_goods_id'] ? $objInfo[0]['shop_goods_id'] : 0,
                                    'product_id'      => $basicMInfo['bm_id'] ? $basicMInfo['bm_id'] : 0,
                                    'shop_product_id' => $objInfo[0]['shop_product_id'] ? $objInfo[0]['shop_product_id'] : 0,
                                    'bn'              => $basicMInfo['material_bn'],
                                    'name'            => $basicMInfo['material_name'],
                                    'cost'            => (float)$objInfo[0]['cost'] ? $objInfo[0]['cost'] : $basicMInfo['cost'],
                                    'price'           => (float)$objInfo[0]['price'],
                                    'pmt_price'       => (float)$objInfo[0]['pmt_price'],
                                    'sale_price'      => (isset($objInfo[0]['sale_price']) && is_numeric($objInfo[0]['sale_price']) && -1 != bccomp($objInfo[0]['sale_price'], 0, 3) ) ? $objInfo[0]['sale_price'] : bcsub($subtotal, (float)$item['pmt_price'],3),
                                    'amount'          => $subtotal,
                                    'weight'          => (float)$objInfo[0]['weight'] ? $objInfo[0]['weight'] : ($basicMInfo['weight'] ? $basicMInfo['weight'] : 0.00),
                                    'quantity'        => $basicMInfo['number']*$quantity,
                                    'addon'           => $addon,
                                    'item_type'       => $item_type,
                                    'delete'          => ($objInfo[0]['delete'] == 'true') ? 'true' : 'false',
                                    'sendnum'         => $sendnum,
                                );
                            }
                        }
                    }else{
                        //找不到对应的基础物料
                        continue;
                    }
                    
                    #修复_淘宝平台_原始属性值 ExBOY
                    if($orderInfo[0]['shop_type'] == 'taobao')
                    {
                        $modify_order_oid[]    = array(
                                                            'order_id'=>$order_id,
                                                            'order_bn'=>$orderInfo[0]['order_bn'],
                                                            'obj_id'=>$objInfo[0]['obj_id'],
                                                            'old_bn'=>$oldPbn[$key],
                                                            'new_bn'=>$salesMInfo['sales_material_bn'],
                                                        );
                    }
                    
                }else{
                    //找不到对应的销售物料
                    continue;
                }

                //原来两层结构都有问题失败的
                if($objInfo[0]['goods_id'] <= 0 || empty($objInfo[0]['bn'])){
                    $newOrder['order_objects'][] = array(
                        'obj_id' => $objInfo[0]['obj_id'],
                        'goods_id'      => $salesMInfo['sm_id'] ? $salesMInfo['sm_id'] : 0,
                        'bn'            => $bn ? $bn : null,
                        'obj_type'      => $obj_type,
                        'obj_alias'     => $this->_obj_alias[$obj_type] ? $this->_obj_alias[$obj_type] : '',
                        'order_items'   => $order_items,
                    );

                    $obj_shop_freeze[$objInfo[0]['obj_id']] = $objInfo[0]['quantity'];
                    $obj_status[$objInfo[0]['obj_id']] = $objInfo[0]['delete'];
                }else{
                    //原来绑定基础物料item有问题失败的
                    $newOrder['order_objects'][] = array(
                        'obj_id' => $objInfo[0]['obj_id'],
                        'order_items'   => $order_items,
                    );
                }

                //注销上一轮的order_items
                unset($order_items);
            }
        }

        if($newOrder){
            $basicMStockLib = kernel::single('material_basic_material_stock');
            $salesMShopFreezeLib = kernel::single('material_sales_material_shop_freeze');

            $newOrder['order_id'] = $order_id;
            $res = $orderObj->save($newOrder);
            if($res){
                foreach($newOrder['order_objects'] as $ok => $obj){
                    if($obj['goods_id'] > 0 && $obj_status[$obj['obj_id']] == 'false'){
                        //obj层 销售物料，店铺货品冻结
                        $salesMShopFreezeLib->freeze($orderInfo[0]['shop_id'], $obj['goods_id'], $obj_shop_freeze[$obj['obj_id']]);
                    }

                    foreach($obj['order_items'] as $ik =>$item){
                        if($item['product_id'] > 0 && $item['delete'] == 'false'){
                            //item层基础物料冻结
                            $basicMStockLib->freeze($item['product_id'],(intval($item['quantity'])-intval($item['sendnum'])));
                        }
                    }
                }
            }
        }
        
        #修复_淘宝平台_原始属性值 ExBOY
        if($modify_order_oid)
        {
            $this->modifyOrderOid($modify_order_oid);
        }

        //修正为正常订单
        if($this->modifyOrder($order_id)){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 失败订单操作日志记录添加
     *
     * @return void
     * @author 
     **/
    function addFailOrderLog($order_id,$opinfo=NULL)
    {
        $oLog = app::get('ome')->model('operation_log');

        $log_id = $oLog->write_log('order_edit@ome',$order_id,"失败订单恢复",'',$opinfo);

        $orderObj = app::get('ome')->model('orders');
        $opObj = app::get('ome')->model('order_pmt');
        $membersObj = app::get('ome')->model('members');
        $paymentsObj = app::get('ome')->model('payments');
        $orders = $orderObj->dump(array('order_id'=>$order_id),"*",array("order_objects"=>array("*",array("order_items"=>array('*')))));

        //优惠方案
        $orders['pmt'] = $opObj->getList('*',array('order_id'=>$order_id));//订单优惠方案
        //会员信息
        $orders['mem_info'] = $membersObj->getRow($orders['member_id']);
        //支付单
        $orders['payments'] = $paymentsObj->getList('*',array('order_id'=>$order_id));

        $orderObj->write_log_detail($log_id,$orders);
    }

    public function getFailOrderByBn($bn=array()){
        $orderObj = app::get('ome')->model('orders');
        $sql = 'SELECT I.order_id FROM sdb_ome_order_objects as I LEFT JOIN '.
            'sdb_ome_orders as O ON I.order_id=O.order_id WHERE O.is_fail=\'true\' and O.edit_status=\'true\' and O.archive=\'1\' and O.status=\'active\' and I.bn in (\''.implode('\',\'',$bn).'\') GROUP BY order_id';
        $rows = $orderObj->db->select($sql);
        return $rows;
    }
    
    /**
     * 修复[淘宝平台]原始属性值
     * PS:拆单开启后,订单部分回写会使用
     *
     * @param  Array    $modify_order_oid
     * @return void
     * @author ExBOY
     **/
    function modifyOrderOid($modify_order_oid)
    {
        if(empty($modify_order_oid))
        {
            return false;
        }
        
        $orderDlyObj    = app::get('ome')->model('order_delivery');
        foreach ($modify_order_oid as $item_id => $item)
        {
            $getData    = $bn_data = array();
    
            #获取淘宝平台的原始数据
            $getData    = $orderDlyObj->dump(array('order_bn'=>$item['order_bn']), 'id, bn');
            
            if(empty($getData['bn']))
            {
                continue;
            }
            
            $bn_data   = unserialize($getData['bn']);
            foreach ($bn_data as $key => $val)
            {
                if($val == $item['old_bn'])
                {
                    $bn_data[$key]    = $item['new_bn'];
                }
            }
            $getData['bn']    = serialize($bn_data);
            
            $orderDlyObj->save($getData);
            
            unset($getData, $bn_data);
        }
        
        return true;
    }
}
